﻿using iTextSharp.text.pdf;
using QDAS;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace QTrans.Company
{
	public class T201809_Nanchang_Getelack : TransferBase
	{
		// 用于显示选择Catalog的窗体 
		public T201809_Nanchang_Getelack() { }

		public override void Initialize()
		{
			base.Initialize();
			CompanyName = "江西南昌格特拉克DCT转换器";
			VertionInfo = "beta 1";
			pd.SupportAutoTransducer = true;
			pd.AddExt("pdf");
		}

		public override bool TransferFile(string inpath)
		{

			convert1(inpath);

			return true;
		}

		// 基本完成，主要问题：
		// 1) 根据 (list[i].Contains("名称") && list[i].Contains("超出值")) 确认开始行是否OK？OK
		// 2) 根据 (list[i].Contains("评价条件")) 确认结束行是否OK？OK
		public bool convert1(string inpath)
		{
			string content = ExtractTextFromPDF(inpath);
			// 去除空行
			string[] lines = content.Split('\n');
			for (int i = 0; i < lines.Length; i++)
				lines[i] = lines[i].Trim(' ', '\0');

			// 移除空数据。
			List<string> list = new List<string>();
			foreach (string s in lines)
				if (!string.IsNullOrEmpty(s))
					list.Add(s);

			while (true)
			{
				if (list[0].Length >= 10)
					break;
				list.RemoveAt(0);
			}

			// 根据“名称 单位 值 超出值”打开开始行
			int startline = 0;
			for (int i = 0; i < list.Count; i++)
			{
				// "名称 单位 值 超出值"
				if (list[i].Contains("名称") && list[i].Contains("超出值")) // 如果是英文版内容应该是对应内容的替代内容
				{
					startline = i;
					break;
				}
			}

			// 根据“评价条件”找到截止行。
			int endline = list.Count;
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].Contains("评价条件")) // 如果是英文版内容应该是“评价条件”的替代内容
				{
					endline = i;
					break;
				}
			}

			Console.WriteLine(list[5] + "\t\t" + list[6]);

			// 获得所有参数，参数内容为 2002, 2142, k0001
			List<string> chs = new List<string>();
			for (int i = startline; i < endline; i++)
			{
				string[] strs = list[i].Split(' ');

				if (list[i].Length > 6 && list[i].Contains(" ") && !list[i].Contains("[") && strs.Length == 3)
				{
					chs.Add(list[i]);
				}
			}

			// 2002, 2142, k0001
			// 读取头问数据
			string[] line1 = list[1].Split(' ');
			string[] line2 = list[3].Split(' ');


			string k1001 = line1[0];
			string k1002 = line1[1];
			string k1053 = line1[line1.Length - 2];
			string k1206 = line1[line1.Length - 1];
			string k1086 = line2[0];
			string k0006 = line2[1];
			string k0004 = line2[2] + ' ' + line2[3];
			string k0007 = line2[4];


			// 由于这一行莫名其妙多了一个换行会被拆分成现行，所以进行了特殊处理。 
			string[] line3 = list[5].Split(' ');

			List<string> inputs = new List<string>();
			if (line3.Length == 4)
				inputs.AddRange(line3);
			else
			{
				inputs.AddRange(list[5].Split(' '));
				inputs.AddRange(list[6].Split(' '));
			}

			string catalogfile = Path.GetFullPath("catalog.dfd");
			if (!File.Exists(catalogfile))
			{
				LogList.Add(new Classes.TransLog(inpath, "", "Catalog 文件不存在。", Classes.LogType.Fail));
				return false;
			}

			string[] additionalInfo = ProcessAdditionalInfo(inputs, Path.GetFullPath("catalog.dfd"));

			string k0008 = additionalInfo[0];
			string k0010 = additionalInfo[1];
			string k0012 = additionalInfo[2];
			string k0005 = additionalInfo[3];
			DateTime date = DateTime.Parse(k0004);


			QFile qf = new QFile();
			qf[1001] = k1001;
			qf[1002] = k1002;
			qf[1053] = k1053;
			qf[1086] = k1086;
			qf[1206] = k1206;


			for (int i = 0; i < chs.Count; i++)
			{
				// Console.WriteLine(list[i]);
				string[] data = chs[i].Split(' ');
				if (data.Length != 3)
					break;

				QCharacteristic qc = new QCharacteristic();
				qf.Charactericstics.Add(qc);
				qc[2002] = data[0];
				qc[2142] = data[1];

				QDataItem qdi = new QDataItem();
				qdi.SetValue(data[2]);
				qdi.date = date;
				qdi[0005] = k0005;
				qdi[0006] = k0006;
				qdi[0007] = k0007;
				qdi[0008] = k0008;
				qdi[0010] = k0010;
				qdi[0012] = k0012;

				qc.data.Add(qdi);
			}

			qf.ToDMode();
			SaveDfqByFilename(qf, Path.GetFileNameWithoutExtension(inpath) + ".dfq");

			return true;
		}

		private string[] ProcessAdditionalInfo(List<string> addinfo, string catalogfile)
		{
			QCatalog catalog = QCatalog.load(catalogfile);
			string[] results = new string[4];

			foreach (string info in addinfo)
			{
				if (catalog.getCatalogPID("K4093", info) > 0)
					results[0] = catalog.getCatalogPID("K4093", info).ToString();
				else if (catalog.getCatalogPID("K4063", info) >= 0)
					results[1] = catalog.getCatalogPID("K4063", info).ToString();
				else if (catalog.getCatalogPID("K4073", info) >= 0)
					results[2] = catalog.getCatalogPID("K4073", info).ToString();
				else if (catalog.getCatalogPID("K4223", info) >= 0)
					results[3] = catalog.getCatalogPID("K4223", info).ToString();
			}

			Console.WriteLine("Addtional info: " + string.Join(",", results));
			/*
XU_FENG_YING change_over		DCT001_028 D_A_10_033Addtional info: 2,4111,124,104change_over		ZHANG_YANG DCT005_025 D_A_09_007Addtional info: 235,4114,122,104change_over		LV_LU_LU DCT005_013 D_A_09_006Addtional info: 228,4113,121,104power_off		DAI_FEN_QIANG DCT005_025 D_A_09_008Addtional info: 253,4114,123,105XIONG_YAO power_off		DCT001_040 D_A_09_006Addtional info: 241,4112,121,105
			 */
			return results;
		}

		public bool convertSilhouette(string inpath)
		{
			string content = ExtractTextFromPDF(inpath);
			// 去除空行
			string[] lines = content.Split('\n');
			for (int i = 0; i < lines.Length; i++)
				lines[i] = lines[i].Trim(' ', '\0');

			// 移除空数据。
			List<string> list = new List<string>();
			foreach (string s in lines)
				if (!string.IsNullOrEmpty(s))
					list.Add(s);

			while (true)
			{
				if (list[0].Length >= 10)
					break;
				list.RemoveAt(0);
			}

			// 读取头问数据
			string[] line1 = list[1].Split(' ');
			string[] line2 = list[3].Split(' ');
			string[] line3 = list[5].Split(' ');

			string k1001 = line1[0];
			string k1002 = line1[1];
			string k1053 = line1[line1.Length - 2];
			string k1206 = line1[line1.Length - 1];
			string k1086 = line2[0];
			string k0006 = line2[1];
			string k0004 = line2[2] + ' ' + line2[3];
			string k0007 = line2[4];
			string k0008 = line3[0];
			string k0010 = line3[1];
			string k0012 = line3[line3.Length - 2];
			string k0005 = line3[line3.Length - 1];
			DateTime date = DateTime.Parse(k0004);

			string catalogfile = Path.GetFullPath("catalog.dfd");
			if (!File.Exists(catalogfile))
			{
				LogList.Add(new Classes.TransLog(inpath, "", "Catalog 文件不存在。", Classes.LogType.Fail));
				return false;
			}

			k0007 = k0007.Contains("内容") ? "SP1" : k0007; // K4253
			k0008 = k0008.Contains("内容") ? "张三" : k0008; // K4093
			k0010 = k0010.Contains("内容") ? "A00" : k0010; // K4063
			k0005 = k0005.Contains("内容") ? "调机 change over" : k0005; // K40	73

			QCatalog catalog = QCatalog.load(catalogfile);
			k0007 = catalog.getCatalogPID("K4253", k0007).ToString();
			k0008 = catalog.getCatalogPID("K4093", k0008).ToString();
			k0010 = catalog.getCatalogPID("K4063", k0010).ToString();
			k0005 = catalog.getCatalogPID("K4223", k0005).ToString();
			k0012 = catalog.getCatalogPID("K4073", k0012).ToString();

			QFile qf = new QFile();
			qf[1001] = k1001;
			qf[1002] = k1002;
			qf[1053] = k1053;
			qf[1086] = k1086;
			qf[1206] = k1206;

			int startRow = 0;
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].Contains("名称") && list[i].Contains("单位"))
				{
					startRow = i + 1;
					break;
				}
			}

			for (int i = startRow; i < list.Count; i++)
			{
				// Console.WriteLine(list[i]);
				string[] data = list[i].Split(' ');
				if (data.Length != 3)
					break;

				QCharacteristic qc = new QCharacteristic();
				qf.Charactericstics.Add(qc);
				qc[2002] = data[0];
				qc[2142] = data[1];

				QDataItem qdi = new QDataItem();
				qdi.SetValue(data[2]);
				qdi.date = date;
				qdi[0005] = k0005;
				qdi[0006] = k0006;
				qdi[0007] = k0007;
				qdi[0008] = k0008;
				qdi[0010] = k0010;
				qdi[0012] = k0012;

				qc.data.Add(qdi);
			}

			qf.ToDMode();
			SaveDfqByFilename(qf, Path.GetFileNameWithoutExtension(inpath) + ".dfq");

			return true;
		}



		/// <summary>
		/// 使用iTextSharp提供的类库打开PDF并返回文本。
		/// </summary>
		/// <param name="pdffilename"></param>
		/// <returns></returns>
		public string ExtractTextFromPDF(string pdffilename)
		{
			StringBuilder text = new StringBuilder();
			try
			{
				PdfReader pdfReader = new PdfReader(pdffilename);
				int numberOfPages = pdfReader.NumberOfPages;
				for (int i = 0; i < pdfReader.NumberOfPages; i++)
				{
					// Page number starts from 1.
					text.Append(iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(pdfReader, i + 1));
				}
				pdfReader.Close();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Extracting text from the input PDf file error. Reason：" + ex.ToString());
			}
			return text.ToString();
		}

	}
}
